package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    /** 
     * @description: 
     * @param: 往order中插入数据，往orderitem表中插入数据
     * @return:
     * @author zhizhuke
     * @date: 2022-01-20 16:53
     */ 
    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext orderContext = (CreateOrderContext) context;
        Order order = new Order();
        String orderId = null;
        try {
            orderId = new GlobalIdGeneratorUtil().getNextSeq("orderId_key", 1);
        } catch (IOException e) {
            log.error("InitOrderHandler.new GlobalIdGeneratorUtil() Occur Exception :" + e);
        }
        order.setOrderId(orderId);
        order.setPayment(orderContext.getOrderTotal());
        order.setPaymentType(1);//todo 支付类型：暂定为在线支付
        order.setPostFee(new BigDecimal(20));//todo 邮费暂定20
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setUserId(orderContext.getUserId());
        order.setBuyerNick(orderContext.getBuyerNickName());
        order.setUniqueKey(orderContext.getUniqueKey());

        //往订单表中插入一条数据
        int affectedRows1 = orderMapper.insertSelective(order);
        //异常处理
        if (affectedRows1<1){
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }

        //往订单商品关联表中插入n条数据

        List<CartProductDto> dtoList = orderContext.getCartProductDtoList();
        List<Long> ids = new ArrayList<>();
        for (CartProductDto cartProductDto : dtoList) {
            OrderItem orderItem = new OrderItem();
            String orderItemId = null;
            try {
                orderItemId = new GlobalIdGeneratorUtil().getNextSeq("orderItemId_key", 1);
            } catch (IOException e) {
                log.error("InitOrderHandler.new GlobalIdGeneratorUtil() Occur Exception :" + e);
            }
            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            int num = cartProductDto.getProductNum().intValue();
            orderItem.setNum(num);
            orderItem.setTitle(cartProductDto.getProductName());
            double price = cartProductDto.getSalePrice().doubleValue();
            orderItem.setPrice(price);
            orderItem.setTotalFee(num*price);
            orderItem.setPicPath(cartProductDto.getProductImg());
            orderItem.setStatus(1);
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            //插入数据
            int affectedRows2 = orderItemMapper.insert(orderItem);
            //异常处理
            if (affectedRows2<1){
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }


            ids.add(cartProductDto.getProductId());
        }

        //更新orderContext
        orderContext.setOrderId(orderId);
        orderContext.setBuyProductIds(ids);


        return true;
    }
}
